package com.lctandil.geophotos.data;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;

import com.google.android.maps.GeoPoint;
import com.lctandil.geophotos.clustering.ImageInfo;

public class ImageLoader {

//	public static final String CAMERA_IMAGE_BUCKET_NAME = Environment
//			.getExternalStorageDirectory().toString() + "/DCIM/Camera";
//	public static final String CAMERA_IMAGE_BUCKET_ID = getBucketId(CAMERA_IMAGE_BUCKET_NAME);

	/**
	 * Matches code in MediaProvider.computeBucketValues. Should be a common
	 * function.
	 */
	public static String getBucketId(String path) {
		return String.valueOf(path.toLowerCase().hashCode());
	}

	public static void loadCameraImages(Context context) {
		final String[] projection = { MediaStore.Images.Media.DATA,
				MediaStore.Images.Media.LATITUDE,
				MediaStore.Images.Media.LONGITUDE,
				MediaStore.Images.Media._ID };
		//final String selection = MediaStore.Images.Media.BUCKET_ID + " = ?";
		//final String[] selectionArgs = { CAMERA_IMAGE_BUCKET_ID };
		final Cursor cursor = context.getContentResolver().query(
				Images.Media.EXTERNAL_CONTENT_URI, projection, null,
				null, null);
		ArrayList<ImageInfo> result = new ArrayList<ImageInfo>();

		try {
			if (cursor.moveToFirst()) {
				int indexlatitude = cursor
						.getColumnIndexOrThrow(MediaStore.Images.Media.LATITUDE);
				int indexlongitude = cursor
						.getColumnIndexOrThrow(MediaStore.Images.Media.LONGITUDE);
				final int dataColumn = cursor
						.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				
				final int idColumn = cursor
						.getColumnIndexOrThrow(MediaStore.Images.Media._ID);

				do {
					if (!cursor.isNull(indexlatitude)) {
						final String data = cursor.getString(dataColumn);
						final double longitude = cursor
								.getDouble(indexlongitude);
						final double latitude = cursor.getDouble(indexlatitude);
						final int id = cursor.getInt(idColumn);
						GeoPoint point = new GeoPoint(((int) (latitude * 1E6)),
								((int) (longitude * 1E6)));

						ImageInfo imageInfo = new ImageInfo(id, point, data);
						result.add(imageInfo);
					}
				} while (cursor.moveToNext());
			}
		} finally {
			cursor.close();
		}
		Cache.getInstance().setPoints(result);
	}

}
